<script setup>
	import { ref, computed, watch, onUnmounted } from 'vue'
	const props = defineProps({
		transName: { // 动画，结合自带动画名称o-fade, o-move-bottom ...
			default: 'o-zoom'
		},
		type: { // 弹出方式 top center bottom left right
			default: 'center'
		},
		show: { // 显示弹窗
			default: false,
		},
		custom: { // 是否自定义
			default: false,
		},
		maskBackground: '',
		maskClick: { // 蒙层点击是否关闭弹窗
			default: true
		},
		mask: { // 是否显示蒙层
			default: true,
		},
		to: {
			default: 'body'
		}
	})
	const styles = computed(() => {
		return {
			background: props.maskBackground || `rgba(0,0,0,.7)`
		}
	})
	const classes = computed(() => {
		return {
			[`o-modal__${props.type}`]: true,
			[`o-modal--events`]: !props.mask
		}
	})
	watch(() => props.show, (n, o) => {
		n ? open() : close()
	})

	const emit = defineEmits(['change', 'changed', 'update:show'])

	const flag = ref(false)

	const open = () => {
		flag.value = true
		emit('change', { value: true })
		emit('update:show', true)

		document.body.style.overflow = 'hidden'
	}
	const close = (type) => {
		if (!props.maskClick && type) return
		flag.value = false
		emit('change', { value: false })
		emit('update:show', false)
		document.body.style.overflow = ''
	}
	const _afterLeave = () => {
		emit('changed', { value: false })
	}


	const destroy = () => { }

	onUnmounted(() => {
		destroy()
	})

	defineExpose({
		open,
		close,
		destroy
	})
</script>

<template>
	<div>
		<Teleport :to="props.to">
			<transition name="o-fade" appear>
				<div class="o-mask" :style="styles" v-if="props.mask && flag" @click="close(true)"></div>
			</transition>
			<transition :name="props.transName" @after-leave="_afterLeave">
				<div class="o-modal" :class="classes" v-if="flag" @click="close(true)">
					<div class="content" @click.stop :class="{'not-custom': !props.custom}">
						<slot></slot>
					</div>
				</div>
			</transition>
		</Teleport>
	</div>
</template>

<style lang="scss" scoped src="../css/index.scss"></style>
<style lang="scss" scoped src="./style.scss"></style>